/**
 * 
 */
package com.sip.comserver.communication.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import com.sip.comserver.communication.CommunicationMessage;

/**
 * @author Dhanushka Ariyasingha.
 */
public class CommunicationClient {

    private InetAddress host = null;
    
    private Socket socket; 

    public CommunicationClient(final String hostName, final int port) throws IOException {
        
//        host = InetAddress.getLocalHost();


//        if (null == hostName)
           host = InetAddress.getByName(hostName);
        
        socket = new Socket(host.getHostName(), port);

    }
    
    public void send(final CommunicationMessage communicationMessage) throws IOException{
        
        final ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        
        objectOutputStream.writeObject(communicationMessage);

    }
    
    public CommunicationMessage read() throws IOException, ClassNotFoundException{
        
        CommunicationMessage communicationMessage = null;
        
        final ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());        
        final Object object=  objectInputStream.readObject();
        
        if(object instanceof CommunicationMessage){
            communicationMessage = (CommunicationMessage) object;
            
        }
        
        return communicationMessage;        
    }
}
